﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MusicOnLine.Models;
using MusicOnLine.Common;
using System.IO;

namespace MusicOnLine.Controllers
{ 
    [MOLAuthorzie(Roles="Admin")]
    public class ManageAlbumController : Controller
    {
        private MusicPlayEntities db = new MusicPlayEntities();

        //
        // GET: /ManageAlbum/

        public ViewResult Index()
        {
            return View();
        }

        public ActionResult QuickSearchAlbum(string term)
        {
            var mode = db.Albums.Where(o => o.AlbumName.Contains(term)).Select(o => new { value=o.AlbumName}).Take(10).ToList();
            return Json(mode, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AlbumList(string g,int PageIndex)
        {
            string s = HttpUtility.UrlDecode(g, System.Text.Encoding.GetEncoding("utf-8"));
            var query = db.Albums.Where(o => o.AlbumName.Contains(s) || o.ArtistName.Contains(s)).OrderByDescending(o => o.CreateDate);
            PageList<Album> model = new PageList<Album>(query, PageIndex, 15);
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /ManageAlbum/Details/5

        public ViewResult Details(int id)
        {
            Album album = db.Albums.Find(id);
            
            return View(album);
        }

        //
        // GET: /ManageAlbum/Create

        //public ActionResult Create()
        //{
        //    SelectList ArtistList = new SelectList(db.Artists.Select(o => new { ID = o.ID, ArtistName = o.ArtistName }).ToList(), "ID", "ArtistName");            
        //    ViewBag.ArtistList = ArtistList;
        //    return View();
        //} 

        //
        // POST: /ManageAlbum/Create

        //[HttpPost]
        //public ActionResult Create(Album album)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        album.ImgUrl = "mrzj.jpg";
        //        db.Albums.Add(album);
        //        db.SaveChanges();
        //        return RedirectToAction("Index");  
        //    }
        //    return View(album);
        //}
        
        //
        // GET: /ManageAlbum/Edit/5
 
        public ActionResult Edit(int id)
        {
            Album album = db.Albums.Find(id);
            ViewBag.ArtistList = new SelectList(db.Artists.OrderBy(o => o.ArtistName).Select(o => new { ArtistID = o.ID, ArtistName = o.ArtistName }).ToList(), "ArtistID", "ArtistName", album.ArtistID);
            return View(album);
        }

        //
        // POST: /ManageAlbum/Edit/5

        [HttpPost]
        public ActionResult Edit(Album album)
        {
            if (ModelState.IsValid)
            {
                string username = HttpContext.User.Identity.Name;
                var file = Request.Files["fileImgUrl"];
                if (file.FileName != "")
                {
                    string ex = System.IO.Path.GetExtension(file.FileName);
                    string fileName = Guid.NewGuid().ToString() + ex;
                    string path = Server.MapPath("~/AlbumImg/");
                    album.ImgUrl = fileName;
                    file.SaveAs(path + fileName);
                }
                album.ModifyDate = DateTime.Now;
                album.ModifyBy = username;
                db.Entry(album).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Details", "ManageAlbum", new {id=album.ID });
            }
            ViewBag.ArtistList = new SelectList(db.Artists.OrderBy(o => o.ArtistName).Select(o => new { ArtistID = o.ID, ArtistName = o.ArtistName }), "ArtistID", "ArtistName", album.ArtistID);
            return View(album);
        }

        //
        // GET: /ManageAlbum/Delete/5
        [MOLAuthorzie(Roles="SuperAdmin")]
        public ActionResult Delete(int id)
        {
            Album album = db.Albums.Find(id);
            return View(album);
        }

        //
        // POST: /ManageAlbum/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            Album album = db.Albums.Find(id);
            db.Albums.Remove(album);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult UploadAlbum()
        {
         
            return View();
        }
        [HttpPost]
        public ActionResult UploadAlbum(AlbumUploadModel albumupModel)
        {
            if (ModelState.IsValid)
            {
                var count = db.Albums.Where(o => o.AlbumName == albumupModel.AlbumName && o.ArtistName == albumupModel.AlbumArtist).Count();
                if (count <= 0)
                {
                    var imgFile = Request.Files[albumupModel.TitleFile];
                    string username = HttpContext.User.Identity.Name;
                    string imgfileName = "";
                    
                    if (imgFile != null)
                    {
                        string imgex = System.IO.Path.GetExtension(imgFile.FileName);
                        imgfileName = Guid.NewGuid().ToString() + imgex;
                        string pathImg = Server.MapPath("/AlbumImg/");
                        string backUpImgPath = System.Configuration.ConfigurationManager.AppSettings["UploadAlubmImg"].Trim();

                        imgFile.SaveAs(pathImg + imgfileName);
                        imgFile.SaveAs(backUpImgPath + imgfileName);
                    }
                    foreach (var item in albumupModel.SongList)
                    {
                        var songfile = Request.Files[item.Location];
                        if (songfile != null)
                        {
                            AACInfo aacinfo = new AACInfo();
                            string ex = System.IO.Path.GetExtension(songfile.FileName);
                            string fileName = Guid.NewGuid().ToString() + ex;
                            string path = System.Configuration.ConfigurationManager.AppSettings["UploadFilePath"].Trim();
                           
                            songfile.SaveAs(path + fileName);

                            aacinfo.Album = albumupModel.AlbumName;
                            aacinfo.AlbumArtist = albumupModel.AlbumArtist;
                            aacinfo.Artist = item.Artist;
                            aacinfo.Genre = albumupModel.Genre;                           
                            aacinfo.ReleaseDate = albumupModel.PublishDate;
                            aacinfo.Year = albumupModel.Year;
                            aacinfo.Location = fileName;
                            aacinfo.Name = item.Name;
                            aacinfo.PlayedCount = 0;
                            aacinfo.IMGPath = imgfileName;
                            aacinfo.CreateBy = username;
                            aacinfo.ModifyBy = username;
                            db.AACInfoes.Add(aacinfo);
                            db.SaveChanges();                            
                        }                      
                    }
                    return RedirectToAction("Index");
                }
                ModelState.AddModelError("", "此专辑已存在服务器上");
            }          
            return View(albumupModel);
        }
        public ActionResult UploadCustControl()
        {
            var GenreList = new SelectList(Common.Common.GetGenre(), "genre", "genre");
            ViewBag.GenreList = GenreList;
            return PartialView("~/Views/CustControl/Upload.cshtml");
        }     

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}